package com.LearnInWorld.controller;

import com.LearnInWorld.config.CookieUtil;
import com.LearnInWorld.config.TokenDecode;
import com.LearnInWorld.entity.Result;
import com.LearnInWorld.entity.StatusCode;
import com.LearnInWorld.service.UserService;
import com.LearnInWorld.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    @RequestMapping("/find/{username}")
    public Result<User> findUser(@PathVariable("username") String username){
       User user= userService.findUser(username);
       return new Result<User>(true, StatusCode.OK,"查询成功",user);
    }

    @PostMapping("/save")
    public Result saveUser(@RequestBody User user){
        userService.saveUser(user);
        return new Result(true,StatusCode.OK,"插入成功");
    }


    @GetMapping("/getUsername")
    public Result<String> getUsername(HttpServletRequest request){
        Map<String, String> map = CookieUtil.readCookie(request, "uid");
        if (map!=null&&map.size()>0){
            String redisToken= stringRedisTemplate.boundValueOps(map.get("uid")).get();
            if (redisToken!=null&&redisToken.length()>0){
                TokenDecode tokenDecode=new TokenDecode();
                String username= tokenDecode.getUserInfo().get("username");
                return new Result<>(true, StatusCode.OK,"获取用户名成功",username);
            }
        }
        return new Result<>(true, StatusCode.LOGINERROR,"获取用户名失败","");
    }

}
